package com.mbl.base.core.aop;

import com.mbl.base.config.enums.ResultEnum;
import com.mbl.base.core.common.dto.MblResult;
import com.mbl.base.core.common.exception.AuthException;
import com.mbl.base.core.common.exception.BaseException;
import com.mbl.base.core.utils.UtilHttp;
import com.mbl.base.core.utils.UtilSecurity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;


/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 *
 * @author lwj
 * @date 2020年2月25日 下午3:19:56
 */
@ControllerAdvice
@Order(-99)
public class GlobalExceptionHandler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 认证异常--认证失败（账号密码错误，账号被冻结，token过期等）
     */
    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public MblResult unAuth(AuthException e) {
        final ResultEnum loginUn = ResultEnum.LOGIN_UN;
        loginUn.setStr(e.getMessage());
        return MblResult.renum(loginUn);
    }

    /**
     * Base 项目主动异常，用于中断当前业务并向前端返回错误信息
     */
    @ExceptionHandler(BaseException.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public MblResult baseAuth(BaseException e) {
        return MblResult.error(e.getCode(),e.getMessage());
    }

    /**
     * 拦截未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
//    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public MblResult notFount(RuntimeException e) {
        if (UtilSecurity.getUser() != null) {
        }
        UtilHttp.getRequest().setAttribute("tip", "服务器未知运行时异常");
        log.error("运行时异常:", e);
        return MblResult.renum(ResultEnum.SERVER_ERR);
    }
}
